package glossos.parsing.fsm;

import glossos.parsing.Parser;
import glossos.parsing.action.Action;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.Reader;

/**
 * A generic finite state machine that uses a {@link java.io.Reader Reader} to read characters. 
 * At each character read it changes its current state. When the last character is read, this
 * state machine executes a final action. This class can be used to parse regular expressions,
 * according to the state graph this state machine depends on.
 * @author Otavio Macedo
 *
 */
public class FiniteStateMachine implements Parser {
	private static Logger logger = Logger.getLogger("glossos.index");

    private Reader reader;
    private State currentState;
    private Action finalAction;

    public FiniteStateMachine(Reader reader, State initialState, Action finalAction) {
        this.reader = reader;
        this.currentState = initialState;
        this.finalAction = finalAction;
    }

    public void parse(){
    	logger.info("Parsing started.");
        try {
            start();
        } catch (IOException e) {
            logger.error("Error indexing: " + e.getMessage());
        }
        logger.info("Parsing finished.");
    }

    /**
     * Starts the machine from the initial state and reads all characters from reader.
     * @throws IOException
     */
    public void start() throws IOException {
        int c;
        while((c = reader.read()) != -1)
            currentState = currentState.next((char)c);
        finalAction.execute('#');
    }
}
